<?php

namespace lico\Tool;

class Helper
{

    /**
     *  判断是否中文
     * @param $str string
     * @return bool
     */
    public static function isChinese($str)
    {
        if (preg_match("/^[\x7f-\xff]+$/", $str)) { //兼容gb2312,utf-8
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检测身份证是否合法以及是否正确
     * @param $cardid string
     * @return bool
     */
    public static function cardCheck($cardid)
    {

        //判断是否为18位
        if (strlen($cardid) != 18) {
            return false;
            exit;
        }
        //取最后一位 该位为校验码
        $lastc = substr($cardid, 17, 1);
        //加权因子
        $wi = array("0" => "7", "1" => "9", "2" => "10", "3" => "5", "4" => "8", "5" => "4", "6" => "2", "7" => "1",
            "8" => "6", "9" => "3", "10" => "7", "11" => "9", "12" => "10", "13" => "5", "14" => "8", "15" => "4", "16" => "2");
        //校验码对照表
        $checkv = array("0" => "1", "1" => "0", "2" => "x", "3" => "9", "4" => "8", "5" => "7", "6" => "6", "7" => "5", "8" => "4", "9" => "3", "10" => "2");
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            //取第$i位于加权因子数组的第$i行 相乘
            $n = substr($cardid, $i, 1);
            $num = (int) $n * (int) $wi[$i];
            $sum += $num;
        }
        //和sum除11取余就为该身份证的最后一位校验码
        $m = $sum % 11;
        if ($checkv[$m] == strtolower($lastc)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 随机数
     * type all,string,number
     * @return string
     */
    public static function getRandStr($length = 6, $type = 'all')
    {

        $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number = '0123456789';

        switch ($type) {
            case 'string':
                $parentStr = $string;
                break;
            case 'number':
                $parentStr = $number;
                break;
            default:
                $parentStr = $string . $number;
                break;
        }
        $len = strlen($parentStr) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $parentStr[$num];
        }
        return $randstr;
    }
}
